package ntd.util.util;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.lang.Opt;
import cn.hutool.log.StaticLog;
import com.itextpdf.text.Document;
import com.itextpdf.text.Image;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.PdfWriter;
import org.apache.poi.hslf.usermodel.*;
import org.apache.poi.sl.usermodel.Slide;
import org.apache.poi.xslf.usermodel.XMLSlideShow;
import org.apache.poi.xslf.usermodel.XSLFSlide;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.List;

public class ToolPoi2 {

    /**
     * pptToPdf
     * @return
     */
    public static byte[] pptToPdf(InputStream inputStream) {
        Document document = null;
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        PdfWriter writer = null;
        try {
            // 读取 PPT/PPTX 文档
            HSLFSlideShow ppt = new HSLFSlideShow(inputStream);

            Dimension pageSize = ppt.getPageSize();

            // 创建 PDF 文档
            document = new Document();
            writer = PdfWriter.getInstance(document, outputStream);
            document.open();

            document.setPageSize(new Rectangle(pageSize.width, pageSize.height));

            // 遍历 PPT/PPTX 中的每一页，并将其添加到 PDF 中
            for (int i = 0; i < ppt.getSlides().size(); i++) {
                Slide slide = ppt.getSlides().get(i);
                BufferedImage image = new BufferedImage(pageSize.width, pageSize.height, BufferedImage.TYPE_INT_RGB);
                Graphics2D graphics = image.createGraphics();
                slide.draw(graphics);
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                ImageIO.write(image, "png", baos);
                Image img = Image.getInstance(baos.toByteArray());
                document.add(img);
            }
            writer.close();
            return outputStream.toByteArray();
        } catch (Exception e) {
            StaticLog.error(e, "[POI][pptToPdf][{}]失败...");
        } finally {
            Opt.ofNullable(outputStream).ifPresent(IoUtil::close);
            Opt.ofNullable(inputStream).ifPresent(IoUtil::close);
            Opt.ofNullable(document).ifPresent(Document::close);
            Opt.ofNullable(writer).ifPresent(PdfWriter::close);
        }
        return null;
    }
}
